package com.zhuangfei.hpuhelper.view;

import java.util.List;

import com.hpu.bean.EmptyRoom;
import com.hpu.bean.RoomBean;
import com.hpu.constants.HttpConstants;
import com.hpu.constants.ShareConstants;
import com.hpu.parser.EmptyRoomParser;
import com.hpu.service.EmptyRoomService;
import com.hpu.service.LoginService;
import com.hpu.tools.JsonTools;
import com.hpu.tools.RoomTools;
import com.hpu.tools.ShareTools;
import com.zhuangfei.hpuhelper.tools.ActivityTools;
import com.zhuangfei.hpuhelper.tools.DefaultHandler;
import com.zhuangfei.hpuhelper.tools.FileTools;
import com.zhuangfei.hpuhelper.tools.OtherUtils;
import com.zhuangfei.hpuhelper.tools.PhoneTools;
import com.zhuangfei.hpuhelper.tools.ReflectTools;
import com.zhuangfei.smartalert.core.LoadAlert;

import cn.lzf.serviceplatform.R;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.LinearLayout.LayoutParams;

public class EmptyRoomActivity extends Activity implements OnClickListener{

	/**
	 * 存放左侧的教学楼容器 以及存放教室实体的集合
	 */
	private LinearLayout roomContainerLayout;
	List<RoomBean> rooms;
	LayoutInflater inflater;
	private LinearLayout backLayout;

	// 右侧显示区域的文本
	private TextView resultTextView1;
	private TextView resultTextView2;
	private TextView resultTextView3;
	private TextView resultTextView4;
	private TextView resultTextView5;

	// 当前加载的空教室
	private RoomBean curRoomBean;
	private int cur=-1;
	
	// 左侧滚动布局
	private ScrollView scrollView;

	// 业务类
	private EmptyRoomService emptyRoomService;
	private LoginService loginService;
	private LoadAlert loadAlert;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_empty_room);
		ActivityTools.setTransparent(this);
		initView();
		initEvent();
		addBuilding();
		
		query(rooms.get(2), 2,false);
	}

	

	/**
	 * 、 初始化布局
	 */
	private void initView() {
		loadAlert = new LoadAlert(this).create();
		loginService = new LoginService(this,handler);
		emptyRoomService = new EmptyRoomService(handler, this);

		rooms = RoomTools.loadInstitude(this, "room.txt");
		roomContainerLayout = (LinearLayout) findViewById(R.id.id_room_container);
		inflater = LayoutInflater.from(this);

		// 滚动布局
		scrollView = (ScrollView) findViewById(R.id.id_room_scrollview);

		// 右侧内容区域
		resultTextView1 = (TextView) findViewById(R.id.id_room_result1);
		resultTextView2 = (TextView) findViewById(R.id.id_room_result2);
		resultTextView3 = (TextView) findViewById(R.id.id_room_result3);
		resultTextView4 = (TextView) findViewById(R.id.id_room_result4);
		resultTextView5 = (TextView) findViewById(R.id.id_room_result5);
		
		backLayout =  (LinearLayout) findViewById(R.id.id_back);
	}
	
	private void initEvent() {
		backLayout.setOnClickListener(this);
	}

	/**
	 * 将教学楼添加到面板
	 */
	private void addBuilding() {
		roomContainerLayout.removeAllViews();
		for (int i = 0; i < rooms.size(); i++) {
			final int temp = i;
			View view = inflater.inflate(R.layout.item_emptyroom_layout, null, false);
			TextView text = (TextView) view.findViewById(R.id.id_room_item_text);
			LinearLayout itemContainerLayout = (LinearLayout) view.findViewById(R.id.id_room_item_container);
			text.setText(rooms.get(i).getInstitude());

			itemContainerLayout.setOnClickListener(new OnClickListener() {

				@Override
				public void onClick(View arg0) {
					boolean isUpdate=(cur==temp?true:false);
					query(rooms.get(temp), temp,isUpdate);
					scrollView.smoothScrollTo(0, OtherUtils.dip2px(EmptyRoomActivity.this, 45) * (temp - 5) + temp);
				}
			});
			roomContainerLayout.addView(view);
		}
	}

	/**
	 * 查询数据
	 * @param roomBean
	 * @param temp 点击的index
	 */
	public void query(RoomBean roomBean, int temp,boolean isUpdate) {
		curRoomBean = roomBean;
		cur=temp;
		
		// 状态切换
		changeStatus(temp);
		// 清空右侧的数据
		initRoomData();
		// 判断本地是否有空教室
		String result = FileTools.readRoom(ShareTools.get(this, ShareConstants.STORE_USER, "默认用户").toString(),
				roomBean.getInstitude());
		if (isUpdate||result == null || result.equals("")) {
			startLoading();
			emptyRoomService.getEmptyRoom(roomBean.getValue());
		} else{
			showData(roomBean.getInstitude());
		}
	}

	/**
	 * 从本地文件读取指定教学楼的数据
	 * 
	 * @param institude
	 */
	protected void showData(final String institude) {
		String result = FileTools.readRoom(ShareTools.get(this, ShareConstants.STORE_USER, "默认").toString(), institude);
		initRoomData();
		EmptyRoomParser emptyRoomParser = new EmptyRoomParser();
		EmptyRoom emptyRoom = emptyRoomParser.parse(result);

		Log.i("Room",result);
		
		if (emptyRoom.getFirstRooms() != null){
			resultTextView1.setText(emptyRoom.getFirstRooms());
		}
		if (emptyRoom.getSecondRooms() != null){
			resultTextView2.setText(emptyRoom.getSecondRooms());
		}
		if (emptyRoom.getThirdRooms() != null){
			resultTextView3.setText(emptyRoom.getThirdRooms());
		}
		if (emptyRoom.getForthRooms() != null){
			resultTextView4.setText(emptyRoom.getForthRooms());
		}
		if (emptyRoom.getFifthRooms() != null){
			resultTextView5.setText(emptyRoom.getFifthRooms());
		}

	}

	@SuppressLint("HandlerLeak")
	DefaultHandler handler = new DefaultHandler(this) {
		public void handleMessage(Message msg) {
			endLoading();
			super.handleMessage(msg);

			switch (msg.what) {
			case HttpConstants.QUERY_ROOM_SUCCESS:
				FileTools.writeRoom(ShareTools.get(EmptyRoomActivity.this, ShareConstants.STORE_USER, "默认用户").toString(),
						curRoomBean.getInstitude(), msg.obj.toString());
				showData(curRoomBean.getInstitude());
				break;
			
			case HttpConstants.VPN_TOOLONG:
				if(handler.isIgnoreVpnExpired()){
					break;
				}
				startLoading();
				loginService.login(ShareTools.get(EmptyRoomActivity.this, ShareConstants.STORE_USER, "").toString(), ShareTools
						.get(EmptyRoomActivity.this, ShareConstants.STORE_PASSWORD1, "").toString(),
						ShareTools.get(EmptyRoomActivity.this, ShareConstants.STORE_PASSWORD2, "").toString());
				break;

			case HttpConstants.LOGIN_SUCCESS:
				ShareTools.put(EmptyRoomActivity.this, ShareConstants.STORE_LOGINCOOKIE, (String) msg.obj);
				emptyRoomService.getEmptyRoom(curRoomBean.getValue());
				break;
			}
		};
	};

	public void initRoomData() {
		resultTextView1.setText("暂无空教室");
		resultTextView2.setText("暂无空教室");
		resultTextView3.setText("暂无空教室");
		resultTextView4.setText("暂无空教室");
		resultTextView5.setText("暂无空教室");
	}

	/**
	 * 当选择教学楼后应该改变状态
	 * @param i
	 */
	@SuppressLint("NewApi")
	private void changeStatus(int pos) {
		int length = roomContainerLayout.getChildCount();
		for (int i = 0; i < length; i++) {
			View view = roomContainerLayout.getChildAt(i);
			TextView text = (TextView) view.findViewById(R.id.id_room_item_text);
			if (i != pos) {
				text.setTextColor(Color.BLACK);
			} else {
				text.setTextColor(Color.RED);
			}
		}
	}

	public void startLoading() {
		loadAlert.show();
	}

	public void endLoading() {
		loadAlert.hide();
	}

	public void goBack(){
		ActivityTools.toBackActivityAnim(this, MenuActivity.class);
	}
	
	@Override
	public void onBackPressed() {
		goBack();
	}

	@Override
	protected void onDestroy() {
		if (loadAlert != null)
			loadAlert.dimiss();
		super.onDestroy();
	}

	@Override
	public void onClick(View arg0) {
		switch (arg0.getId()) {
		case R.id.id_back:
			goBack();
			break;

		default:
			break;
		}
	}
}
